/**
 * 
 */
package com.itinsys.enma.manager.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.itinsys.enma.dao.ResourceDAO;
import com.itinsys.enma.domain.Environment;
import com.itinsys.enma.domain.Resource;
import com.itinsys.enma.domain.response.ResourceResponse;
import com.itinsys.enma.manager.ResourceManager;
import com.itinsys.enma.manager.ResponseManager;

/**
 * @author rperez
 *
 */
public class ResourceManagerImpl implements ResourceManager{

	@Autowired
	private ResourceDAO resourceDAO;
	@Autowired
	private ResponseManager responseManager;
	
	@Override
	public ResourceResponse getAllResources() {
		ResourceResponse response = new ResourceResponse();
		List<Resource> resources = resourceDAO.getAll();
		if(resources.isEmpty())
			responseManager.prepareResponse(response, ResourceResponse.RESOURCE_NOT_FOUND);
		else{
			responseManager.prepareResponse(response, ResourceResponse.OK);
			response.setResource(resources);
		}
		return response;
	}


	@Override
	public ResourceResponse addResource(Resource resource) {
		
		ResourceResponse response = new ResourceResponse();
			if(resourceDAO.addResource(resource))		
				response=getAllResources();
			else
				responseManager.prepareResponse(response, ResourceResponse.ERROR);
		return response;
	}

	@Override
	public ResourceResponse updateResource(Resource resource) {
		ResourceResponse response = new ResourceResponse();
		Resource resourceToUpdate = resourceDAO.getById(resource.getId());
		resourceToUpdate.setDescription(resource.getDescription());
		
		if(resourceDAO.updateResourcel(resourceToUpdate))		
			response=getAllResources();
		else
			responseManager.prepareResponse(response, ResourceResponse.ERROR);

		return response;
	}

	
	@Override
	public ResourceResponse deleteResource(Resource resource) {
		ResourceResponse response = new ResourceResponse();
		List<Environment> environments = resourceDAO.getEnvironmentByResource(resource.getId());

		if (environments.isEmpty()) {
			resource = resourceDAO.getById(resource.getId());
			if(resourceDAO.deleteResource(resource))		
				response = getAllResources();
			else
				responseManager.prepareResponse(response, ResourceResponse.ERROR);
		} else {
			this.responseManager.prepareResponse(response, ResourceResponse.RESOURCE_HAVE_ENVIRONMENT);
		}	
		
		
		return response;
	}

	

}
